#include "bsp_rtc.h"

uint8_t BCD2DEC(uint8_t bcd){
	return (bcd-(bcd>>4)*6);
}
uint8_t DEC2BCD(uint8_t dec){
	return (dec+(dec/10)*6);
}

rtc_timestamp_struct rtc_timestamp;
rtc_parameter_struct rtc_initpara;
uint32_t RTCSRC_FLAG = 0;
#define BKP_VALUE    0x32F4

SemaphoreHandle_t rtc_MuxSem = NULL;

void bsp_rtc_init(void){
	rcu_periph_clock_enable(RCU_PMU);
	pmu_backup_write_enable();
	
	rcu_osci_on(RCU_LXTAL);
	rcu_osci_stab_wait(RCU_LXTAL);
	rcu_rtc_clock_config(RCU_RTCSRC_LXTAL);
	
	rcu_periph_clock_enable(RCU_RTC);
	rtc_register_sync_wait();
	
	RTCSRC_FLAG = GET_BITS(RCU_BDCTL, 8, 9);
	if((BKP_VALUE != RTC_BKP0) || (0x00 == RTCSRC_FLAG)){
		RTC_BKP0 = BKP_VALUE;
		rcu_all_reset_flag_clear();
		
		rtc_initpara.year = 24;
		rtc_initpara.month = 11;
		rtc_initpara.date = 29;
		rtc_initpara.day_of_week = 5;
		rtc_initpara.hour = 15;
		rtc_initpara.minute = 40;
		rtc_initpara.second = 50;
		rtc_initpara.factor_asyn = 0x7F;
		rtc_initpara.factor_syn = 0xFF;
		rtc_initpara.am_pm = RTC_PM;
		rtc_initpara.display_format = RTC_24HOUR;
		
		rtc_init(&rtc_initpara);
	}
	
	rtc_MuxSem = xSemaphoreCreateMutex();
}
void bsp_rtc_show_date_time(void){
	xSemaphoreTake(rtc_MuxSem,portMAX_DELAY);
	rtc_parameter_struct tst;
	rtc_current_time_get(&tst);
	debug_printf("date_time = %d-%d-%d:%d-%d-%d<%d><%d>\r\n",BCD2DEC(tst.year),BCD2DEC(tst.month),BCD2DEC(tst.date),BCD2DEC(tst.hour),BCD2DEC(tst.minute),BCD2DEC(tst.second),BCD2DEC(tst.day_of_week),BCD2DEC(tst.am_pm));
	xSemaphoreGive(rtc_MuxSem);
}
void bsp_set_rtc_date_time(uint8_t year, uint8_t month, uint8_t date, uint8_t week, uint8_t hour, uint8_t min, uint8_t sec){
	xSemaphoreTake(rtc_MuxSem,portMAX_DELAY);
	rtc_parameter_struct ts;
	
	ts.year = DEC2BCD(year);
	ts.month = DEC2BCD(month);
	ts.date = DEC2BCD(date);
	ts.day_of_week = DEC2BCD(week);
	ts.hour = DEC2BCD(hour);
	ts.minute = DEC2BCD(min);
	ts.second = DEC2BCD(sec);
	ts.factor_asyn = 0x7F;
	ts.factor_syn = 0xFF;
	if(hour < 12)
		ts.am_pm = RTC_AM;
	else
		ts.am_pm = RTC_PM;
	ts.display_format = RTC_24HOUR;
	rtc_init(&ts);
	xSemaphoreGive(rtc_MuxSem);
}